import _ from 'lodash'

export function toPropertyList(object) {
    let props = []
    function parse(object, paths = []) {
        for (let key in object) {
            if (object.hasOwnProperty(key)) {
                const value = object[key]
                if (_.isPlainObject(value)) {
                    parse(value, [...paths, key])
                } else if (_.isArray(value)) {
                    value.forEach((item, index) => {
                        parse(item, [...paths, key + '[' + index + ']'])
                    })
                } else {
                    props.push({
                        paths: [...paths, key],
                        value
                    })
                }
            }
        }
    }
    parse(object)
    return props
}

export function toCommandLine(args) {
    const commands = {}
    while (args.length > 0) {
        let arg = args.shift()
        let key, value
        if (arg.startsWith('--')) {
            const e = arg.indexOf('=')
            if (e != -1) {
                key = arg.substring(2, e)
                value = arg.substring(e + 1)
            } else {
                key = arg.substring(2)
                let nextValue = args.at(0)
                if (nextValue) {
                    if (nextValue.startsWith('-')) {
                        value = true
                    } else {
                        value = args.shift()
                    }
                }
            }
        } else if (arg.startsWith('-')) {
            key = arg.substring(1)
            let nextValue = args.at(0)
            if (nextValue) {
                if (nextValue.startsWith('-')) {
                    value = true
                } else {
                    value = args.shift()
                }
            }
        }
        commands[key] = value
    }
    return commands
}
